package com.dongdongshop.seckillmq.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.cart.service.CartService;
import com.dongdongshop.front.pojo.TbSeckillGoods;
import com.dongdongshop.front.pojo.TbSeckillOrder;
import com.dongdongshop.seckillmq.util.IdWorker;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Component
@RocketMQMessageListener(topic = "SECKILLGOODS",consumerGroup = "seckill_group")
public class SeckillMq implements RocketMQListener<Map> {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(Map map) {
        System.out.println("秒杀抢购mq接收成功");
        Long seckillId = Long.parseLong(map.get("seckillId").toString());
        String username = map.get("username").toString();

        TbSeckillGoods seckillGoods = (TbSeckillGoods) redisTemplate.boundHashOps("seckillGoods").get(seckillId);
        //生成订单
        long seckillOrderId = idWorker.nextId();
        TbSeckillOrder order = new TbSeckillOrder();
        order.setId(seckillOrderId);
        order.setCreateTime(new Date());
        order.setMoney(seckillGoods.getCostPrice());
        order.setSeckillId(seckillId);
        order.setSellerId(seckillGoods.getSellerId());
        order.setUserId(username);
        order.setStatus("0");//等待付款状态
        //先放缓存，等用户真正购买成功后再同步到数据库
        redisTemplate.boundHashOps("seckillOrder").put(username+""+seckillId,order);
        //购买成功以后，限制一个用户只能买一件
        redisTemplate.boundHashOps("seckillGoodsOnlyOne"+username+seckillId);

    }
}
